package com.team2.outpatient_sys.config;

import com.team2.outpatient_sys.exception.AuthenticationEntryPointImpl;
import com.team2.outpatient_sys.filter.LoginFilter;
import com.team2.outpatient_sys.util.NoopPasswordEncoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SpringBootSecurityConfig extends WebSecurityConfigurerAdapter {
    // 注入登录验证的过滤器
    @Autowired
    private LoginFilter loginFilter;

    // 配置密码加密处理
    @Bean
    public PasswordEncoder passwordEncoder() {
        // return new BCryptPasswordEncoder();

        // 测试用，用于处理明文密码
        return new NoopPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .csrf().disable()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and().authorizeRequests()
            .antMatchers("/**/login").anonymous().antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
            .anyRequest().authenticated();

        // 配置指定过滤器在SpringBoot Security的过滤器之间执行
        http.addFilterBefore(loginFilter, UsernamePasswordAuthenticationFilter.class);

        // 配置Security的异常处理
        http.exceptionHandling().authenticationEntryPoint(new AuthenticationEntryPointImpl());

//        http.cors();
    }

    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
}
